package com.adresvseti.wallpaperoid.services;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import com.adresvseti.wallpaperoid.constants.Settings;

import android.os.AsyncTask;
import android.util.Log;

/**
 * Downloads binary from url in separate thread.
 *
 */
public class DownloadBinaryTask extends AsyncTask<String, Void, InputStream> {

	private IDownloadBinaryCallback successCallback;
	
	
	public DownloadBinaryTask(IDownloadBinaryCallback successCallback)
	{
		this.successCallback = successCallback;
	}
	
	
	@Override
	protected InputStream doInBackground(String... urls) {
		
		try {
            return downloadUrl(urls[0]);
        } catch (IOException e) {
            return null;
        }
	}
	
    @Override
    protected void onPostExecute(InputStream result) {
    	successCallback.success(result);
    }
		
    private InputStream downloadUrl(String downloadUrl) throws IOException {
	     
		InputStream is = null;

		try {
			URL url = new URL(downloadUrl);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setReadTimeout(60000);
			conn.setConnectTimeout(60000);
			conn.setRequestMethod("GET");
			conn.setDoInput(true);

			// connecting
			conn.connect();

			int response = conn.getResponseCode();
			Log.d(Settings.DEBUG_TAG, url + ": " + response);
			
			is = conn.getInputStream();

			return is;
		} 
		catch (Exception e)
		{
			return null;
		}
	 }

}
